package com.yunfangdata.util;

import com.yunfangdata.domain.Employee;
import com.yunfangdata.domain.SystemLog;
import com.yunfangdata.service.ISystemLogService;
import org.apache.shiro.SecurityUtils;
import org.aspectj.lang.JoinPoint;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.Arrays;
import java.util.Date;

public class SystemLogAspect {

    @Autowired
    private ISystemLogService systemLogService;

    public void write(JoinPoint jp){

        //自己systemlogservice操作不需要记录日志
        if (jp.getTarget() instanceof ISystemLogService) {
            return;
        }
        SystemLog systemlog = new SystemLog();

        //操作时间
        systemlog.setOpTime(new Date());

        //获取当前用户
        //用户登录时 用户信息还没有存到subject中

        if("queryCurrentUserByEmpUsername".equals(jp.getSignature().getName()) || "queryPortraitByUsername".equals(jp.getSignature().getName())){
            return;
        }
        Employee employee = (Employee) SecurityUtils.getSubject().getPrincipal();
        systemlog.setOpUser(employee.getRealName());
        //当前操作方法
        systemlog.setFunction(jp.getTarget().getClass().getName() + "." + jp.getSignature().getName());
        //当前方法参数
        systemlog.setParams(Arrays.toString(jp.getArgs()));
        systemlog.setParams("");
        //操作用户 ip
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) requestAttributes;
        systemlog.setIp(servletRequestAttributes.getRequest().getRemoteAddr());
        systemLogService.save(systemlog);
    }

}
